package com.yuwei.user

import android.os.CountDownTimer
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.yuwei.base.RoutePath
import com.yuwei.common.mvi.BaseViewActivity
import com.yuwei.user.databinding.ActivityCodeBinding
import com.yuwei.user.entity.GetPermissions
import java.util.*

@Route(path = RoutePath.MODULE_CODE_LOGIN_ACTIVITY)
class CodeActivity : BaseViewActivity<ActivityCodeBinding>() {

    override fun initView() {
        val randomNumber=generateRandomNumber()
        binding.tvHelp.setOnClickListener {
            ARouter.getInstance().build(RoutePath.MODULE_LOGIN_HELP_ACTIVITY).navigation()
        }
        val countDownTimer=object :CountDownTimer(60000,1000){
            override fun onTick(p0: Long) {
                binding.tvPhoneLoginTime.setText("${p0/1000}")
            }

            override fun onFinish() {
                binding.tvPhoneLoginTime.setText("重新获取")
            }

        }
        binding.tvPhoneLoginTime.setOnClickListener {
            ToastUtils.showLong("验证码：${randomNumber}")
            countDownTimer.start()
        }
        binding.btnCodeLogin.setOnClickListener {
            if (binding.etCodeLogin.text.toString().equals(randomNumber)&& GetPermissions.hasContactsPermission(this)){
                ToastUtils.showLong("登录成功")
                ARouter.getInstance().build(RoutePath.MAIN_ACTIVITY).navigation()
            } else if (!binding.etCodeLogin.text.toString().equals(randomNumber)){
                ToastUtils.showLong("无效验证码")
            }else{
                ARouter.getInstance().build(RoutePath.MODULE_PHONE_BOOK_ACTIVITY).navigation()
            }
        }
        binding.ivBack.setOnClickListener {
            finish()
            countDownTimer.cancel()
        }
    }

    override fun initData() {

    }


    private fun generateRandomNumber(): String {
        val random = Random()
        val number = StringBuilder()
        for (i in 0 until 6) {
            number.append(random.nextInt(10))
        }
        return number.toString()
    }
}